package org.x.user.controller;

import jakarta.validation.constraints.Pattern;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.x.common.config.Result;
import org.x.common.enums.LogAsync;
import org.x.common.utils.SmsService;

@RestController
@RequestMapping("/api/sms")
public class SmsController {

    private static final Logger log = LoggerFactory.getLogger(SmsController.class);

    private final SmsService smsService;

    public SmsController(SmsService smsService) {
        this.smsService = smsService;
    }

    /**
     * 发送短信验证码
     *
     * @param phone 手机号
     * @return 操作结果
     */
    @LogAsync("发送短信验证码")
    @PostMapping("/sendCode")
    public Result sendSmsCode(
            @RequestParam @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") String phone) {
        log.info("Request received to send SMS code to phone: {}", phone);
        try {
            smsService.sendSmsCode(phone);
            log.info("SMS code sent successfully to phone: {}", phone);
            return Result.ok("验证码已发送，请注意查收");
        } catch (Exception e) {
            log.error("Failed to send SMS code to phone {}: {}", phone);
            return Result.error( 500, "验证码发送失败");
        }
    }
}
